<?php
// +-----------------------------------------------------------------------------------------------
// | 简易CMS
// +-----------------------------------------------------------------------------------------------
// | 内容控制器
// +-----------------------------------------------------------------------------------------------
// | Author: IT果农 <htmambo@163.com> <http://www.haolie.net>
// +-----------------------------------------------------------------------------------------------
// | Version $Id$
// +-----------------------------------------------------------------------------------------------
namespace app\admin\controller;
use app\admin\model\AuthGroup;

/**
 * 后台内容控制器
 */
class Article extends AdminController {
    public function edit(){
        $aid = input('aid', 0, 'intval');
        $catid = input('catid', 0, 'intval');
        $task = input('task', '', 'trim');

        $model = model('ArticleTitle');
        $acModel = model('ArticleContent');

        $cfModel = model('Customfields');

        $customfields = $cfModel->lists();

        $article = $article_content = array();

        if ($aid) {
            if (!$article = $model->find($aid)) {
                return $this->error('对不起，您指定的文章不存在！');
            }
            $tags = db('Tags')->alias('a')
                ->join('__TAGSLIST__ b','b.tagid=a.tagid', 'LEFT')
                ->where("a.itemid='$aid' AND a.tagtype='article'")
                ->select();
            if ($tags) {
                $article ['tagname'] = array();
                foreach ($tags as $v) {
                    $article ['tagname'] [] = $v ['tagname'];
                }
                $article ['tagname'] = implode(',', $article ['tagname']);
            }
            $this->pageTitle = '编辑文章：'.$article['title'];
        } else {
            $this->pageTitle = '添加文章';
        }

        $cat = array();
        $catid = 1;
        if ($catid) {
            $cat = category_remake($catid);
        }

        $catModel = model('Categories');
        $categories = $catModel->lists();
        if ($catid && empty($categories [$catid])) {
            return $this->error('没有找到指定的分类！');
        }
        if (empty($article) && $catid && $categories [$catid] ['disallowpublish']) {
            return $this->error('此分类中不允许发布文章!', dreferer());
        }
        if ($aid) {
            $catid = intval($article ['catid']);
        }
//        if (!check_articleperm($catid, $aid)) {
//            return $this->error('你无权操作当前文章!');
//        }
        $page = max(1, input(config('paginate.var_page'), 1, 'intval'));
        $start = $page - 1;
        $pageselect = '';

        $cate = $categories [$catid];

        if ($article) {
            if ($task == 'addpage' || $task == 'add') {
                $article_content = array();
            } else {
                $article_content = $acModel->where("aid='$aid'")->order('pageorder')->limit($start, 1)->find();
                if (!$article_content) {
                    $article_content = array();
                }
            }
            // @todo 不知道为什么代码总是被直接转化出来，郁闷！
            if (isset($article_content ['content'])) {
                $article_content ['content'] = htmlentities($article_content ['content'], ENT_COMPAT, 'utf-8');
            }
            $article ['attach_image'] = $article ['attach_file'] = '';
            $atModel = model('Attachment');
            $lists = $atModel->where("aid='$aid'")->order('attachid')->select();
            foreach ((array) $lists as $value) {
                if ($value ['isimage']) {
                    $article ['attach_image'] .= get_uploadcontent($value);
                } else {
                    $article ['attach_file'] .= get_uploadcontent($value);
                }
            }
            if ($article ['contents'] > 0) {
                $pageselect = '<select name="pageorder">';
                $pageselect .= "<option value=\"0\">" . 'End' . "</option>";
                for ($i = 1; $i <= $article ['contents']; $i ++) {
                    $selected = ($task != 'addpage' && $page == $i) ? ' selected' : '';
                    $pageselect .= "<option value=\"$i\"$selected>$i</option>";
                }
                $pageselect .= '</select>';
            }


            //$multi = multi($article ['contents'], 1, $page, "index.php?group=user&option=article&task=edit&aid=$aid", 0, 5);
        }
        $cfhtml = '';
        $tbodynum = 0;
        if ($customfields) {
            foreach ($customfields as $cfkey => $cfvalue) {
                if (empty($article ['customfieldid'])) {
                    if ($cfvalue ['isdefault']) {
                        $article ['customfieldid'] = $cfvalue ['customfieldid'];
                    }
                }
                $cfhtmlselect [$cfvalue ['customfieldid']] = $cfvalue ['name'];
                $cfarr = $cfvalue ['customfieldtext'];
                if (is_array($cfarr) && $cfarr) {
                    if (!empty($article ['customfieldid']) && $article ['customfieldid'] == $cfvalue ['customfieldid']) {
                        $tbodydisplay = '';
                        if (empty($article ['customfieldtext'])) {
                            $thecfarr = array();
                        } else {
                            $thecfarr = unserialize($article ['customfieldtext']);
                        }
                    } else {
                        $tbodydisplay = 'none';
                        $thecfarr = array();
                    }
                    $tbodynum ++;
                    $cfhtml .= '<div id="cf_' . $tbodynum . '" class="customfield clearfix" style="display:' . $tbodydisplay . ';">';
                    foreach ($cfarr as $ckey => $cvalue) {
                        $inputstr = '';
                        if (empty($thecfarr [$ckey]))
                            $thecfarr [$ckey] = '';
                        $cfoptionarr = array();
                        if ($cvalue ['type'] == 'select' || $cvalue ['type'] == 'checkbox') {
                            $cfoptionarr = processOptions($cvalue ['option']);
                        }
                        switch ($cvalue ['type']) {
                            case 'input' :
                            case 'url' :
                                $inputstr = '<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . ']" type="text" size="80" value="' . $thecfarr [$ckey] . '" class="px" />';
                                break;
                            case 'select' :
                                $inputstr = '<select name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . ']"';
                                $inputstr .= '>' . "\n";
                                foreach ($cfoptionarr as $tmpkey => $tmpvalue) {
                                    if (is_string($thecfarr[$ckey]) && strlen($thecfarr [$ckey]) > 0 && $tmpkey == $thecfarr [$ckey]) {
                                        $tmpselected = ' selected';
                                    } else {
                                        $tmpselected = '';
                                    }
                                    $inputstr .= '<option value="' . $tmpkey . '"' . $tmpselected . '>' . $tmpvalue . '</option>' . "\n";
                                }
                                $inputstr .= '</select>';
                                break;

                            case 'urls' :
                                $str = '<div id="addurls_' . $cfvalue ['customfieldid'] . '_' . $ckey . '" style="border: 1px solid #ccc;clear:both;">';
                                if (isset($thecfarr [$ckey] ['url']) && is_array($thecfarr [$ckey] ['url'])) {
                                    $notes = $thecfarr [$ckey] ['note'];
                                    $urls = $thecfarr [$ckey] ['url'];
                                    foreach ($urls as $k => $v) {
                                        $str .= '描述<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . '][note][]" type="text" size="80" value="' . $notes [$k] . '" class="px" style="margin: 4px 0" /><br />';
                                        $str .= '地址<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . '][url][]" type="text" size="80" value="' . $v . '" class="px" style="margin: 4px 0" /><br />';
                                    }
                                } else {
                                    $str .= '描述<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . '][note][]" type="text" size="80" value="" class="px" style="margin: 4px 0" /><br />';
                                    $str .= '地址<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . '][url][]" type="text" size="80" value="" class="px" style="margin: 4px 0" /><br />';
                                }
                                $strx = '';
                                $strx .= "描述<input name=\\'customfieldtext[" . $cfvalue ['customfieldid'] . "][$ckey][note][]\\' type=\\'text\\' size=\\'80\\' value=\\'\\' class=\\'px\\' style=\\'margin: 4px 0\\' /><br />";
                                $strx .= "地址<input name=\\'customfieldtext[" . $cfvalue ['customfieldid'] . "][$ckey][url][]\\' type=\\'text\\' size=\\'80\\' value=\\'\\' class=\\'px\\' style=\\'margin: 4px 0\\' /><br />";
                                $inputstr = $str . '</div><input type="button" class="btn" value="' . 'Add' . '" onclick="adddivcustomfield(\'addurls_' . $cfvalue ['customfieldid'] . '_' . $ckey . '\', \'' . $strx . '\');" />';
                                break;
                            case 'input' :
                            case 'url' :
                                $inputstr = '<input name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . ']" type="text" size="80" value="' . $thecfarr [$ckey] . '" class="px" />';
                                break;
                            case 'textarea' :
                                $inputstr = '<textarea name="customfieldtext[' . $cfvalue ['customfieldid'] . '][' . $ckey . ']" rows="5" cols="60">' . $thecfarr [$ckey] . '</textarea>';
                                break;
                        }
                        $cfhtml .= '<dl><dt>' . $cvalue ['name'] . '</dt><dd>' . $inputstr . '</dd></dl>';
                    }
                    $cfhtml .= '</div>';
                }
            }
        }
        $cfhtml = str_replace('</div></div>', '</div>', $cfhtml);
        $this->assign('cfhtml', $cfhtml);
        $this->assign('article', $article);
        $this->assign('article_content', $article_content);
        return $this->fetch('form');
    }

    function delPage() {
        $model = model('ArticleTitle');
        $acmodel = model('ArticleContent');
        $aid = input('aid', 0, 'intval');
        if (!$aid) {
            return $this->error('你没有指定要删除的文章！');
        }
        if (!$article = $model->find($aid)) {
            return $this->error('对不起，您指定的文章不存在！');
        }
//        if (!check_articleperm($article ['catid'], $aid)) {
//            return $this->error('你无权操作当前文章!');
//        }


        $pageorder = intval($_GET ['pageorder']);
        $cid = intval($_GET ['cid']);

        if ($aid && $cid) {
            $count = $acmodel->where("aid='$aid'")->count();
            if ($count > 1) {
                $acmodel->where("cid='$cid' AND aid='$aid'")->delete();
                $model->where("aid='$aid'")->setDec('contents');
            } else {
                return $this->error('当前编辑的是最后一页，无法删除！');
            }
        }
        return $this->error('操作完成，请返回!', 1, "index.php?group=user&option=article&task=edit&aid=$aid");
    }

    function onDelete() {
        if (!$aid) {
            return $this->error('你无权操作当前文章!');
        }
//        if (!check_articleperm($article ['catid'], $aid)) {
//            return $this->error('你无权操作当前文章!');
//        }

        if (submitcheck('deletesubmit')) {
            include FUNC_PATH . 'delete.func.php';
            $article = deletearticle(array(
                intval($_POST ['aid'])
                    ), intval($_POST ['optype']));
        }
        return $this->error('指定的文章已经被删除！', "index.php?group=user&option=article&task=category&catid={$article[0][catid]}");
    }

    /**
    * 回收站管理
    *
    */
    public function getRecyle(){
        $map = array('status'=>-1);
        return $this->lists('ArticleTitle', $map);
    }
    /**
    * 删除指定的文章
    *
    */
    public function del(){
        $aid = input('aid', '', 'trim');
        if(!$aid) {
            return $this->error('请选择要删除的文章！');
        }
        $aids = explode(',', $aid);
        return $this->delete('ArticleTitle', array('aid'=>array('IN', implode(',', $aids))));
    }

    /**
     * 分类文档列表页
     * @param integer $cate_id 分类id
     * @param integer $position 推荐标志
     */
    public function index(){
        return $this->fetch();
    }

    /**
     * 文章列表
     *
     */
    public function getDatas(){
        $map=array();
        /**
         * 这里要搞一下权限的细分，比如分类授权的，只能编辑自己的等等
         */
        return $this->lists('ArticleTitle', $map);
    }
}